<template>
	<view class="add-leave-page">
		<!-- 自定義導航欄 -->
		<u-navbar
			:title="pageTitle"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
			<template #right>
				<u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
				<u-icon name="search" size="20" color="#333" @click="showSearch" style="margin-left: 20rpx;"></u-icon>
			</template>
		</u-navbar>

		<!-- 表單內容 -->
		<view class="form-content">
			<!-- 请假类型 -->
			<view class="form-field">
				<text class="field-label required">请假类型</text>
				<view 
					class="select-field"
					@click="selectLeaveType"
					:class="{ 'disabled': loadingLeaveTypes }"
				>
					<text class="select-text">{{ formData.leaveType || (loadingLeaveTypes ? '加载中...' : '请选择') }}</text>
					<text class="select-arrow">›</text>
				</view>
				<view v-if="loadingLeaveTypes" class="loading-tip">
					<text class="loading-text">加载中...</text>
				</view>
			</view>

			<!-- 请假开始时间 -->
			<view class="form-field">
				<text class="field-label required">请假开始时间</text>
				<view 
					class="select-field"
					@click="selectStartTime"
				>
					<text class="select-text">{{ formData.startTime || '请选择' }}</text>
					<text class="select-arrow">›</text>
				</view>
			</view>

			<!-- 请假结束时间 -->
			<view class="form-field">
				<text class="field-label required">请假结束时间</text>
				<view 
					class="select-field"
					@click="selectEndTime"
				>
					<text class="select-text">{{ formData.endTime || '请选择' }}</text>
					<text class="select-arrow">›</text>
				</view>
			</view>

			<!-- 请假时长(天) -->
			<view class="form-field">
				<text class="field-label">请假时长(天)</text>
				<u-input
					v-model="formData.durationDays"
					placeholder="请输入"
					type="number"
					:maxlength="3"
					:border="false"
					:custom-style="{ padding: '20rpx', backgroundColor: '#FFFFFF', borderRadius: '8rpx', border: '1rpx solid #E0E0E0', textAlign: 'right' }"
					:confirm-type="'done'"
					:hold-keyboard="false"
				/>
			</view>

			<!-- 请假时长(小时) -->
			<view class="form-field">
				<text class="field-label">请假时长(小时)</text>
				<u-input
					v-model="formData.durationHours"
					placeholder="0"
					type="number"
					:maxlength="3"
					:border="false"
					:custom-style="{ padding: '20rpx', backgroundColor: '#FFFFFF', borderRadius: '8rpx', border: '1rpx solid #E0E0E0', textAlign: 'right' }"
					:confirm-type="'done'"
					:hold-keyboard="false"
				/>
			</view>

			<!-- 有薪请假时长(天) -->
			<view class="form-field">
				<text class="field-label">有薪请假时长(天)</text>
				<u-input
					v-model="formData.durationPaidDays"
					placeholder="请输入"
					type="number"
					:maxlength="3"
					:border="false"
					:custom-style="{ padding: '20rpx', backgroundColor: '#FFFFFF', borderRadius: '8rpx', border: '1rpx solid #E0E0E0', textAlign: 'right' }"
					:confirm-type="'done'"
					:hold-keyboard="false"
				/>
			</view>

			<!-- 有薪请假时长(小时) -->
			<view class="form-field">
				<text class="field-label">有薪请假时长(小时)</text>
				<u-input
					v-model="formData.durationPaidHours"
					placeholder="0"
					type="number"
					:maxlength="3"
					:border="false"
					:custom-style="{ padding: '20rpx', backgroundColor: '#FFFFFF', borderRadius: '8rpx', border: '1rpx solid #E0E0E0', textAlign: 'right' }"
					:confirm-type="'done'"
					:hold-keyboard="false"
				/>
			</view>

			<!-- 请假事由 -->
			<view class="form-field">
				<text class="field-label">请假事由</text>
				<u-input
					v-model="formData.description"
					placeholder="请输入"
					type="textarea"
					:maxlength="200"
					:show-count="true"
					:auto-height="true"
					:border="false"
					:custom-style="{ padding: '20rpx', backgroundColor: '#FFFFFF', borderRadius: '8rpx', border: '1rpx solid #E0E0E0', minHeight: '120rpx' }"
				/>
			</view>
		</view>

		<!-- 底部确认按钮 -->
		<view class="bottom-button-container">
			<button 
				class="confirm-button"
				@click="submitForm"
				:disabled="!isFormValid"
			>
				确定
			</button>
		</view>
	</view>

	<!-- 请假类型选择器 -->
	<u-picker
		:show="showLeaveTypePicker"
		:columns="[leaveTypeOptions.map(item => item.label)]"
		@confirm="onLeaveTypeConfirm"
		@cancel="showLeaveTypePicker = false"
		:title="'选择请假类型'"
		:confirm-color="'#FF6B35'"
		:cancel-color="'#666666'"
	/>

	<!-- 开始时间选择器 -->
	<u-datetime-picker
		:show="showStartTimePicker"
		mode="datetime"
		v-model="startTimeValue"
		@confirm="onStartTimeConfirm"
		@cancel="showStartTimePicker = false"
		:custom-style="{ 
			confirmColor: '#FF6B35',
			cancelColor: '#666666'
		}"
		:min-date="new Date().getTime()"
		:max-date="new Date('2030-12-31').getTime()"
		:close-on-click-overlay="false"
		:show-toolbar="true"
		:title="'选择开始时间'"
		:z-index="1000"
	/>

	<!-- 结束时间选择器 -->
	<u-datetime-picker
		:show="showEndTimePicker"
		mode="datetime"
		v-model="endTimeValue"
		@confirm="onEndTimeConfirm"
		@cancel="showEndTimePicker = false"
		:custom-style="{ 
			confirmColor: '#FF6B35',
			cancelColor: '#666666'
		}"
		:min-date="new Date().getTime()"
		:max-date="new Date('2030-12-31').getTime()"
		:close-on-click-overlay="false"
		:show-toolbar="true"
		:title="'选择结束时间'"
		:z-index="1000"
	/>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'

import { userStore } from '@/stores/userStore'
import { leaveApi } from '@/api/api-helper.js'

// 表单数据
const formData = reactive({
	leaveType: '',
	leaveTypeId: '', // 请假类型ID，用于提交到API
	startTime: '',
	endTime: '',
	durationDays: '',
	durationHours: '',
	durationPaidDays: '',
	durationPaidHours: '',
	description: ''
})

// 页面参数
const pageParams = ref({
	id: ''
})



// 请假类型选项
const leaveTypeOptions = ref([])
const loadingLeaveTypes = ref(false)

// 时间选择器状态
const showLeaveTypePicker = ref(false)
const showStartTimePicker = ref(false)
const showEndTimePicker = ref(false)

// 时间选择器值
const startTimeValue = ref('')
const endTimeValue = ref('')

// 计算属性：判断是否为编辑模式
const isEditMode = computed(() => {
	return !!pageParams.value.id
})

// 计算属性：页面标题
const pageTitle = computed(() => {
	return isEditMode.value ? '编辑' : '新增'
})

// 计算属性：提交按钮文字
const submitButtonText = computed(() => {
	return isEditMode.value ? '保存' : '确定'
})

// 计算属性：表单是否有效
const isFormValid = computed(() => {
	return formData.leaveTypeId && formData.startTime && formData.endTime && formData.description.trim() !== ''
})

// 页面加载时获取参数
onLoad((options) => {
	console.log('=== onLoad 触发 ===')
	console.log('页面参数 options:', options)
	
	// 直接从 options 获取参数
	if (options) {
		pageParams.value.id = options.id || ''
	}
	
	console.log('页面加载完成，pageParams:', pageParams.value)
	
	// 如果是编辑模式，加载现有数据
	if (isEditMode.value) {
		loadEditData()
	}
	
	// 加载请假类型列表
	loadLeaveTypes()
	

})

// 加载编辑数据
const loadEditData = async () => {
	if (!pageParams.value.id) return
	
	try {
		const response = await leaveApi.getLeaveDetail(pageParams.value.id)
		if (response.code === 200) {
			const data = response.data
			
			// 映射请假数据字段
			formData.leaveType = data.leaveTypeName || ''
			formData.leaveTypeId = data.leaveTypeId || ''
			formData.startTime = data.startTime || ''
			formData.endTime = data.endTime || ''
			formData.durationDays = data.durationDays ? String(data.durationDays) : ''
			formData.durationHours = data.durationHours ? String(data.durationHours) : ''
			formData.durationPaidDays = data.durationPaidDays ? String(data.durationPaidDays) : ''
			formData.durationPaidHours = data.durationPaidHours ? String(data.durationPaidHours) : ''
			formData.description = data.description || ''
			
			console.log('已加载请假编辑数据:', formData)
		} else {
			uni.showToast({
				title: response.msg || '加载数据失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('加载请假编辑数据失败:', error)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	}
}



// 加载请假类型列表
const loadLeaveTypes = async () => {
	loadingLeaveTypes.value = true
	try {
		const response = await leaveApi.getLeaveTypeList()
		console.log('请假类型API响应:', response)
		
		if (response && response.code === 200) {
			const list = response.data || []
			
			// 根据接口返回的数据结构映射字段
			leaveTypeOptions.value = list.map(item => ({
				value: item.id || '', // 使用 id 作为值
				label: item.fullName || '未知类型' // 使用 fullName 作为显示标签
			}))
			
			console.log('处理后的请假类型列表:', leaveTypeOptions.value)
		} else {
			console.error('获取请假类型失败:', response?.msg)
			// 如果API失败，使用默认类型
			leaveTypeOptions.value = [
				{ value: '年假', label: '年假' },
				{ value: '病假', label: '病假' },
				{ value: '事假', label: '事假' },
				{ value: '调休', label: '调休' },
				{ value: '婚假', label: '婚假' },
				{ value: '产假', label: '产假' },
				{ value: '陪产假', label: '陪产假' },
				{ value: '丧假', label: '丧假' },
				{ value: '其他', label: '其他' }
			]
		}
	} catch (error) {
		console.error('获取请假类型失败:', error)
		// 如果网络错误，使用默认类型
		leaveTypeOptions.value = [
			{ value: '年假', label: '年假' },
			{ value: '病假', label: '病假' },
			{ value: '事假', label: '事假' },
			{ value: '调休', label: '调休' },
			{ value: '婚假', label: '婚假' },
			{ value: '产假', label: '产假' },
			{ value: '陪产假', label: '陪产假' },
			{ value: '丧假', label: '丧假' },
			{ value: '其他', label: '其他' }
		]
	} finally {
		loadingLeaveTypes.value = false
	}
}



// 页面显示时的处理
onShow(() => {
	console.log('=== onShow 触发 ===')
	// 请假申请页面不需要特殊的数据回传处理
})

// 方法
const showMoreOptions = () => {
	uni.showActionSheet({
		itemList: ['保存草稿', '预览', '设置'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
		}
	})
}

const showSearch = () => {
	uni.showToast({
		title: '搜索功能',
		icon: 'none'
	})
}

// 选择请假类型
const selectLeaveType = () => {
	if (loadingLeaveTypes.value) {
		uni.showToast({
			title: '正在加载请假类型，请稍候',
			icon: 'none'
		})
		return
	}
	showLeaveTypePicker.value = true
}

// 请假类型确认
const onLeaveTypeConfirm = (e: any) => {
	if (e.value && e.value.length > 0) {
		const selectedLabel = e.value[0]
		// 根据选中的标签找到对应的值
		const selectedOption = leaveTypeOptions.value.find(option => option.label === selectedLabel)
		if (selectedOption) {
			formData.leaveType = selectedOption.label // 显示标签
			formData.leaveTypeId = selectedOption.value // 保存值用于提交
		} else {
			formData.leaveType = selectedLabel
			formData.leaveTypeId = selectedLabel
		}
	}
	showLeaveTypePicker.value = false
}

// 选择开始时间
const selectStartTime = () => {
	startTimeValue.value = formData.startTime ? new Date(formData.startTime).getTime() : new Date().getTime()
	showStartTimePicker.value = true
}

// 开始时间确认
const onStartTimeConfirm = (e: any) => {
	if (e.value) {
		const date = new Date(e.value)
		formData.startTime = formatDateTime(date)
		// 自动计算时长
		calculateDuration()
	}
	showStartTimePicker.value = false
}

// 选择结束时间
const selectEndTime = () => {
	endTimeValue.value = formData.endTime ? new Date(formData.endTime).getTime() : new Date().getTime()
	showEndTimePicker.value = true
}

// 结束时间确认
const onEndTimeConfirm = (e: any) => {
	if (e.value) {
		const date = new Date(e.value)
		formData.endTime = formatDateTime(date)
		// 自动计算时长
		calculateDuration()
	}
	showEndTimePicker.value = false
}

// 格式化日期时间
const formatDateTime = (date: Date) => {
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 计算请假时长
const calculateDuration = () => {
	if (formData.startTime && formData.endTime) {
		const startDate = new Date(formData.startTime)
		const endDate = new Date(formData.endTime)
		
		if (startDate < endDate) {
			const diffTime = endDate.getTime() - startDate.getTime()
			const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
			const diffHours = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
			
			formData.durationDays = diffDays.toString()
			formData.durationHours = diffHours.toString()
		}
	}
}







// 提交表单
const submitForm = async () => {
	// 验证必填字段
	if (!formData.leaveTypeId) {
		uni.showToast({
			title: '请选择请假类型',
			icon: 'none'
		})
		return
	}
	
	if (!formData.startTime) {
		uni.showToast({
			title: '请选择请假开始时间',
			icon: 'none'
		})
		return
	}
	
	if (!formData.endTime) {
		uni.showToast({
			title: '请选择请假结束时间',
			icon: 'none'
		})
		return
	}
	
	if (!formData.description.trim()) {
		uni.showToast({
			title: '请输入请假事由',
			icon: 'none'
		})
		return
	}
	
	// 验证时间逻辑
	const startDate = new Date(formData.startTime)
	const endDate = new Date(formData.endTime)
	
	if (startDate >= endDate) {
		uni.showToast({
			title: '结束时间必须晚于开始时间',
			icon: 'none'
		})
		return
	}
	
	try {
		uni.showLoading({
			title: isEditMode.value ? '保存中...' : '提交中...',
			mask: true
		})
		
		const openId = userStore.getOpenId()
		if (!openId) {
			uni.hideLoading()
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}
		
		const submitData = {
			openId: openId,
			leaveTypeId: formData.leaveTypeId, // 使用请假类型ID
			startTime: formData.startTime,
			endTime: formData.endTime,
			durationDays: parseInt(formData.durationDays) || 0, // 请假时长(天)
			durationHours: parseInt(formData.durationHours) || 0, // 请假时长(小时)
			durationPaidDays: parseInt(formData.durationPaidDays) || 0, // 有薪请假时长(天)
			durationPaidHours: parseInt(formData.durationPaidHours) || 0, // 有薪请假时长(小时)
			description: formData.description.trim() // 请假事由
		}
		
		let response
		if (isEditMode.value) {
			// 编辑模式
			response = await leaveApi.updateLeave({
				...submitData,
				id: pageParams.value.id
			})
		} else {
			// 新增模式
			response = await leaveApi.createLeave(submitData)
		}
		
		uni.hideLoading()
		
		if (response.code === 200) {
			uni.showToast({
				title: isEditMode.value ? '保存成功' : '提交成功',
				icon: 'success'
			})
			
			// 延迟返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			uni.showToast({
				title: response.msg || (isEditMode.value ? '保存失败' : '提交失败'),
				icon: 'none'
			})
		}
	} catch (error) {
		uni.hideLoading()
		console.error('提交表单失败:', error)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	}
}

onMounted(() => {
	console.log('=== onMounted 触发 ===')
	console.log('请假新增页面加载完成')
	console.log('当前formData:', formData)
})
</script>

<style lang="scss" scoped>
.add-leave-page {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

/* 表單內容 */
.form-content {
	padding: 20rpx;
	padding-bottom: 200rpx;
}

/* 表單字段 */
.form-field {
	background-color: #FFFFFF;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 字段標籤 */
.field-label {
	display: block;
	padding: 20rpx 20rpx 10rpx 20rpx;
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
	
	&.required::before {
		content: '*';
		color: #FF4757;
		margin-right: 8rpx;
	}
}

/* 加载提示 */
.loading-tip {
	padding: 0 20rpx 20rpx 20rpx;
}

.loading-text {
	font-size: 24rpx;
	color: #999999;
	font-style: italic;
}

/* 選擇字段 */
.select-field {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15rpx 20rpx 20rpx 20rpx;
	cursor: pointer;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: #F8F8F8;
	}
	
	&:active {
		background-color: #F0F0F0;
	}
	
	&.disabled {
		cursor: not-allowed;
		opacity: 0.6;
		
		&:hover {
			background-color: transparent;
		}
		
		&:active {
			background-color: transparent;
		}
	}
}

.select-text {
	font-size: 28rpx;
	color: #333333;
	flex: 1;
}

.select-arrow {
	font-size: 24rpx;
	color: #999999;
	margin-left: 10rpx;
}

/* 輸入字段樣式覆蓋 */
:deep(.u-input) {
	background-color: transparent !important;
	border: none !important;
	
	.u-input__content__field-wrapper__field {
		background-color: transparent !important;
	}
}

/* 底部確認按鈕容器 */
.bottom-button-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #FFFFFF;
	padding: 20rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	border-top: 1rpx solid #F0F0F0;
	z-index: 99;
}

/* 確認按鈕 */
.confirm-button {
	width: 100%;
	padding: 24rpx;
	background-color: #007AFF;
	color: #FFFFFF;
	font-size: 32rpx;
	font-weight: bold;
	border-radius: 12rpx;
	border: none;
	transition: all 0.3s ease;
	
	&:active {
		background-color: #0056CC;
		transform: scale(0.98);
	}
	
	&:disabled {
		background-color: #CCCCCC;
		color: #999999;
		cursor: not-allowed;
	}
}

/* 響應式設計 */
@media (max-width: 750rpx) {
	.form-content {
		padding: 15rpx;
	}
	
	.field-label {
		font-size: 26rpx;
		padding: 18rpx 18rpx 8rpx 18rpx;
	}
	
	.select-field {
		padding: 12rpx 18rpx 18rpx 18rpx;
	}
	
	.select-text {
		font-size: 26rpx;
	}
	
	.confirm-button {
		font-size: 30rpx;
		padding: 20rpx;
	}
}
</style>

